<template>
  <el-table :data="sortedMeterList" @row-click="handleMeterClick" highlight-current-row :current-row-key="currentRowKey"
    ref="tableRef" border>
    <el-table-column align="center" label="表计编号" min-width="120">
      <template #default="scope">
        <span :style="{ color: isLeakedMeter(scope.row) ? 'red' : '' }">
          {{ scope.row.meter_code }}
        </span>
      </template>
    </el-table-column>

    <el-table-column align="center" prop="installation_location" label="安装位置" min-width="100" show-overflow-tooltip>
      <template #default="scope">
        <div class="ellipsis-cell">
          <span>{{ scope.row.installation_location || '-' }}</span>
        </div>
      </template>
    </el-table-column>

    <el-table-column align="center" prop="supply_region" label="供应点位" min-width="100" show-overflow-tooltip>
    </el-table-column>

    <el-table-column align="center" prop="value" :formatter="value => value.value + 'm³'" label="最小流量" min-width="120"
      sortable />

    <el-table-column align="center" prop="time" label="最小流量时间" min-width="140">
      <template #default="scope">
        <span :style="{ color: isLeakedMeter(scope.row) ? 'red' : '' }">
          {{ dayjs(scope.row.time).format("MM-DD HH:mm") }}
        </span>
      </template>
    </el-table-column>

    <!-- 新增漏损状态列 -->
    <el-table-column align="center" label="漏损状态" min-width="100">
      <template #default="scope">
        <el-tag v-if="isLeakedMeter(scope.row)" type="danger" size="small">
          漏损
        </el-tag>
        <el-tag v-else-if="scope.row.is_drain_considerd === false" type="info" size="small">
          不计入统计
        </el-tag>
        <el-tag v-else type="success" size="small">
          正常
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column fixed="right" align="center" label="操作" width="100">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleMeterClick(scope.row)">
          查看详情
        </el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { useAreaStore } from "@/stores/area";
import dayjs from "dayjs";
import { ref, computed, watch, inject } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const props = defineProps({
  meterList: {
    type: Array,
    default: () => [],
  },
  selectedMeterId: {
    type: Number,
    default: null,
  },
  height: {
    type: Number,
    default: 550,
  },
});

// 注入统一的漏水判断函数
const isLeakedMeter = inject('isLeakedMeter');

const sortedMeterList = computed(() => {
  let localMeterList = props.meterList && props.meterList.length > 0
    ? [...props.meterList]
    : [];

  // 修改排序逻辑：漏损表计优先排在前面
  localMeterList.sort((a, b) => {
    const aIsLeaked = isLeakedMeter(a);
    const bIsLeaked = isLeakedMeter(b);

    // 第一优先级：漏损状态排序（漏损的排在前面）
    if (aIsLeaked && !bIsLeaked) {
      return -1; // a 是漏损，b 不是，a 排在前面
    }
    if (!aIsLeaked && bIsLeaked) {
      return 1; // b 是漏损，a 不是，b 排在前面
    }

    // 第二优先级：如果漏损状态相同，按流量值降序排序
    if (a.value > b.value) {
      return -1;
    } else if (a.value < b.value) {
      return 1;
    } else {
      return 0;
    }
  });

  return localMeterList;
});

const emit = defineEmits(["rowClick", "toggleView"]);
const tableRef = ref(null);

const currentRowKey = computed(() => {
  return props.selectedMeterId;
});

watch(
  () => props.selectedMeterId,
  (newVal) => {
    if (!newVal && tableRef.value) {
      // 当 selectedMeterId 为 null 时，清除当前行的高亮
      tableRef.value.setCurrentRow(null);
    }
  }
);

const areaStore = useAreaStore();

function handleMeterClick(row) {
  // 判断当前是否在漏水检测页面
  const currentRoute = router.currentRoute.value.path;
  if (!currentRoute.includes('/warning-center/water-leakage-analysis')) {
    // 如果不在漏水检测页面，则进行跳转
    router.push({
      name: "WaterLeakageAnalysis",
      query: {
        id: row.id,
      },
    });
  }
  // 无论是否跳转，都发送事件通知父组件
  emit("rowClick", row);
}
</script>

<style scoped>
.el-table {
  height: 100%;
  min-height: 450px;
  width: 100%;
}

/* 确保表格容器可以横向滚动 */
.el-table__body-wrapper {
  overflow-x: auto !important;
}

.el-table__body {
  height: 100% !important;
  min-width: 100% !important;
}

.el-table__row.current-row {
  background-color: #ecf5ff !important;
}

.ellipsis-cell {
  max-width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 优化滚动条样式（可选） */
.el-table__body-wrapper::-webkit-scrollbar {
  height: 8px;
}

.el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 4px;
}

.el-table__body-wrapper::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}
</style>